import getComponentRootDom from "./getCompRootDom"
import Icon from "@/components/Icon"
import styles from "./showMessage.module.scss"
/**
 * 弹出消息
 * @param {String} content 消息内容
 * @param {String} type 消息类型 info error success warn
 * @param {Number} duration 多久后消失
 * @param {HTMLElement} container 容器；如果未传，则显示到页面顶部
 */
export default function(options = {}) {
  const content = options.content || ""
  const type = options.type || "info"
  const duration = options.duration || 2000
  const container = options.container || document.body
  // 创建消息新元素
  const div = document.createElement("div")
  const iconDom = getComponentRootDom(Icon, { type: type } )
  div.innerHTML = `<span class="${styles.icon}">${iconDom.outerHTML}</span><div>${content}</div>`
  const typeClassName = styles[`message-${type}`] 
  div.className = `${styles.message} ${typeClassName}`
  // 容器的position是否为static
  if(options.container) {
      if(getComputedStyle(container).position === 'static') {
    container.style.position = 'relative'
  }
  }
  // 将消息div添加到容器中
  container.appendChild(div)
  // 利用reflow导致浏览器强行渲染此div
  div.clientHeight
  // 使消息提示div回到正常位置
  div.style.opacity = 1
  div.style.transform = `translate(-50%, -50%)`
  // 等一段时间消失
  setTimeout(() => {
    div.style.opacity = 0
    div.style.transform = `translate(-50%, -50%) translateY(-25px)`
    div.addEventListener("transitionend", () => {
      div.remove()
      // 运行回调函数
      options.callback && options.callback()
    }, { once: true })
  }, duration)
}